<?php
// +----------------------------------------------------------------------
// | SwiftPHP [ JUST DO ONE THING WELL ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2017  http://swiftphp.zhongwenyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhongwenyu <zhongwenyu1987@163.com> <http://www.zhongwenyu.com>
// +----------------------------------------------------------------------
// | Times: 2017/2/23 16:21
// +----------------------------------------------------------------------
namespace swift;
use swift\db\Connection;

class Db{
    //  数据库连接实例
    private static $instance = [];
    // 查询次数
    public static $queryTimes = 0;
    // 执行次数
    public static $executeTimes = 0;

    /**
     * 数据库初始化 并取得数据库类实例
     * @static
     * @access public
     * @param mixed         $config 连接配置
     * @param bool|string   $name 连接标识 true 强制重新连接
     * @return Connection
     * @throws Exception
     */
    public static function connect($config = [], $name = false){
        // 对每个数据库配置实行每一连接标识
        if($name === false){
            $name = md5(serialize($config));
        }
        if($name === true || !isset(self::$instance[$name])){
            // 获取数据库连接参数
            $option = self::parseConfig($config);
            if(empty($option['type'])){
                throw new \Exception("数据库类型未定义！");
            }
            $class = false !== strpos($option['type'],'\\') ? $option['type'] : '\\swift\\db\\driver\\' . ucwords($option['type']);
            if($name === true){
                return new $class($option);
            } else {
                self::$instance[$name] = new $class($option);
            }
        }
        return self::$instance[$name];
    }

    /**
     * 数据库连接参数解析
     * @static
     * @access private
     * @param mixed $config
     * @return array
     */
    private static function parseConfig($config){
        if(empty($config)){
            $config = Config::get('database');
        }elseif(is_string($config) && false === strpos($config , '/')){
            // 读取配置参数
            $config = Config::get($config);
        }
        if(is_string($config)){
            return self::parseDsn($config);
        }else{
            return $config;
        }
    }

    /**
     * DSN解析
     * 格式： mysql://username:passwd@localhost:3306/DbName?charset=utf8&prefix=yw_
     * @static
     * @access private
     * @param string $dsnStr
     * @return array
     */
    private static function parseDsn($dsnStr){
        $info = parse_url($dsnStr);
        $dsn = [
            'type'     => $info['scheme'],
            'username' => isset($info['user']) ? $info['user'] : '',
            'password' => isset($info['pass']) ? $info['pass'] : '',
            'hostname' => isset($info['host']) ? $info['host'] : '',
            'hostport' => isset($info['port']) ? $info['port'] : '',
            'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
        ];
        $params = [];
        if(isset($info['query'])){
            parse_str($info['query'],$params);
            $dsn = array_merge($dsn,$params);
        }
        return $dsn;
    }

    // 调用驱动类方法
    public static function __callStatic($method , $args){
        return call_user_func_array([self::connect() , $method] , $args);
    }
}